<template>
  <div class="app-container">
    <el-form  class="query-wrapper" :model="queryParams" inline>
      <el-form-item prop="brand">
        <el-input v-model="queryParams.brand" style="width: 180px" placeholder="Brand"  clearable />
      </el-form-item>
      <el-form-item prop="name">
        <el-input v-model="queryParams.name" style="width: 180px" placeholder="Model" clearable />
      </el-form-item>
      <el-form-item> 
        <el-button type="primary" icon="search" @click="search">{{ $t("ship.button.search") }}</el-button>
        <SearchReset :query-params="queryParams" @reset="resetQuery"></SearchReset>
      <!-- <el-button type="primary" @click="addClickEvent"   v-hasPermi="['measured:edit']">
        {{ $t("ship.button.plus") }}
      </el-button> -->

      <!-- <el-button type="primary" @click="uploadFileForm" v-hasPermi="['measured:edit']">Import</el-button>
      <input id="upload-spec-file" type="file" accept=".xls,.xlsx" v-hasPermi="['measured:edit']"  v-show="false" @change="uploadFile($event)" /> -->
      </el-form-item>
    </el-form>
  </div>
  <el-table class="unfreight-table" :border="true" ref="tableRef" row-key="id" virtual :data="listData"  show-overflow-tooltip    
    @sort-change="handleSortChange">
    <el-table-column prop="brand" label="Brand" width="160" />
    <el-table-column prop="name" label="Model" width="160" />
    <el-table-column prop="cargoType" label="Cargo Type" width="250" /> 
    <el-table-column prop="description" label="Description(详细描述)" width="160" />  
    <el-table-column prop="measureLength" label="Length(m)" width="90" >
      <template #default="scope">
        <span :class="scope.row.measureLength!=scope.row.declareLength?'diff-measure':''">{{ scope.row.measureLength }}</span>
      </template>
    </el-table-column>
    <el-table-column prop="measureWidth" label="Width(m)">
      <template #default="scope">
        <span :class="scope.row.measureWidth!=scope.row.declareWidth?'diff-measure':''">{{ scope.row.measureWidth }}</span> 
      </template>
    </el-table-column> 
    <el-table-column prop="measureHeight" label="Height(m)" width="90">
      <template #default="scope">
        <span :class="scope.row.measureHeight!=scope.row.declareHeight?'diff-measure':''">{{ scope.row.measureHeight }}</span>  
      </template>
    </el-table-column>
    <el-table-column prop="measureUnitCbm" label="Unit Cbm" />
    <el-table-column prop="weight" label="Unit Weight" width="100" />
    <!-- <el-table-column prop="unitWeight" label="Weight(kg)" /> -->
 
    <el-table-column prop="photo" label="Photo" min-width="180" v-hasPermi="['measured:edit']">
      <template #default="scope" >
        <div class="image_content">
          <el-upload
          class="upload-demo"
          action="#"
          multiple
          :limit="5"
          accept=".jpg,.png,.jpeg"
          :http-request="HttpRequest"
          :on-success="handleSuccess"
          :before-upload="handleBeforeUpload"
          :on-remove="handleRemove"
          :show-file-list="false"
          list-type="picture"
          style="margin-right: 4px"
        >
          <el-button @click="handleChange(scope.row, true)">
            <el-icon class="avatar-uploader-icon"><Upload /></el-icon
          ></el-button>
        </el-upload>
        <el-image
          v-for="item in scope.row.photos"
          style="width: 40px; height: 30px; margin-right: 5px; cursor: pointer; vertical-align: top"
          :src="item"
          :zoom-rate="1.2"
          :max-scale="4"
          :min-scale="0.2"
          :preview-src-list="scope.row.photos"
          :initial-index="0"
          :preview-teleported="true"
          v-model="isShowImage"
          @show="clickImage(scope.row)"
          @switch="switchImage"
          fit="cover"
        /> 
        </div>
      
      </template>
    </el-table-column>
    <el-table-column label="Tally Report" width="260" v-hasPermi="['measured:edit']">
      <template #default="scope">
        <div style="display: flex;">
          <el-upload
          class="upload-demo"
          action="#"
          :limit="5"
          accept=".pdf"
          :http-request="HttpRequest"
          :on-success="handleSuccess"
          :on-remove="handleRemove"
          :before-upload="handleBeforeUpload"
          :show-file-list="false"
        >
          <el-button type="" @click="handleChange(scope.row, false)" v-if="tallys.length < 5"><el-icon><Upload /></el-icon></el-button>
          <!-- <template #tip>
            <div class="el-upload__tip">pdf files with a size less than 1Mb.</div>
          </template> -->
        </el-upload>

        <transition-group style="margin-left: 10px;" class="upload-file-list el-upload-list el-upload-list--text" name="el-fade-in-linear" tag="ul">
        <li :key="index" class="fielupload el-upload-list__item ele-upload-list__item-content" @mouseenter="mouseoverHandle(true)" @mouseleave="mouseoverHandle(false)" v-for="(url, index) in scope.row.tallys">
          <div>
            <span v-if="isDel" style="margin:0 5px 0 0 ;cursor:pointer;color: #ff9e40;" @click="uploadRemove(url,scope.row)" >X</span>
            <a class="el-icon-download"   @click="pdfPreviewHandle(url)" > {{ getFileName(url) }} </a>
             
            <!-- <span @click="handlePreviewPdf(url.includes(COS_CDN_URL) ? url : 'https://booking-1257832417.cos.ap-' + url, getFileName(url))" >
              <el-icon><ZoomOut /></el-icon>
              {{ getFileName(url) }} 
            </span> -->
          </div>
        </li>
         </transition-group>
        </div>
       
		 
        <!-- <span class="btn-primary" @click="uploadPictures(scope.row, false)"> Upload</span>&nbsp;&nbsp;
        <span class="btn-primary" @click="downloadPictures(scope.row, false)"> Download </span> -->
      </template>
    </el-table-column>
    <el-table-column prop="vesselVoyage" label="Vessel & Voyage" width="200" />
    <el-table-column prop="remark" label="Remarks" width="100" />
    <el-table-column label="Operation" fixed="right" width="140"  v-hasPermi="['measured:edit']">
      <template #default="scope">
        <span class="btn-primary" @click="editClickEvent(scope.row)">{{ $t("ship.button.edit") }}</span>&nbsp;&nbsp;
        <!-- <span class="btn-primary"  @click="removeClickEvent(scope.row.id)">{{ $t("ship.button.remove") }}</span> -->
      </template>
    </el-table-column>
  </el-table>

  <pagination
    v-show="total > 0"
    :total="total"
    :page="queryParams.pageNum"
    :limit="queryParams.pageSize"
    @pagination="pageQuery"
    style="float: right"
  />

  <el-dialog :width="1000" destroy-on-close draggable :title="dialogTitle" v-model="dialogFormVisible">
    <el-form :model="formParam" :rules="rules" ref="custForm">
      <el-row>
        <el-col :span="12">
          <el-form-item label="brand" label-width="120px" prop="brand" required>
            <el-select v-model="formParam.brand" filterable allow-create placeholder="choose brand" style="width: 100%" @change="handleBrand">
              <el-option :key="item.name" :label="item.name" :value="item.name" v-for="item in brands"> </el-option>
            </el-select>
          </el-form-item>
        </el-col>

        <el-col :span="12">
          <el-form-item label="Model" label-width="120px" prop="name" required>
            <el-input v-model="formParam.name"></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>  
      
        <!-- <el-col :span="12">
          <el-form-item label="FUEL TYPE" label-width="120px" prop="evType" required>
            <el-select v-model="formParam.evType" filterable clearable allow-create>
              <el-option :key="item" :label="item" :value="item" v-for="item in evTypes"> </el-option>
            </el-select>
          </el-form-item>
        </el-col> -->
        <el-col :span="12">
          <el-form-item label="Cargo Type" label-width="120px" prop="cargoType">
            <el-select v-model="formParam.cargoType" filterable clearable allow-create style="width: 100%;">  
              <el-option v-for="item in cargo_type" :key="item.label" :label="item.label" :value="item.label" />
            </el-select> 
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="Description" label-width="120px" prop="description">
             <el-input type="textare" v-model="formParam.description" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="Length(m)" label-width="120px" prop="measureLength">
            <el-input-number v-model="formParam.measureLength" :precision="3" :min="0" :max="100" />
          </el-form-item>
        </el-col> 
        <el-col :span="12">
          <el-form-item label="Width(m)" label-width="120px" prop="measureWidth" required>
            <el-input-number v-model="formParam.measureWidth" :precision="3" :min="0" :max="100" />
          </el-form-item>
        </el-col> 
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="Height(m)" label-width="120px" prop="cargoType">
            <el-input-number v-model="formParam.measureHeight" :precision="3" :min="0" :max="100" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="Vessel & Voyage" label-width="120px" prop="vesselVoyage">
            <el-input v-model="formParam.vesselVoyage"   :max="100" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="Remarks" label-width="120px" prop="remark">
            <el-input v-model="formParam.remark" :precision="3" :min="0" :max="100" />
          </el-form-item>
        </el-col>
      </el-row>  
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="dialogFormVisible = false">{{ $t("ship.button.cancel") }}</el-button>
        <el-button @click="resetForm" type="warning">{{ $t("ship.button.reset") }}</el-button>
        <el-button type="primary" @click="submitForm">{{ $t("ship.button.submit") }}</el-button>
      </span>
    </template>
  </el-dialog>

  <el-dialog :width="500" destroy-on-close draggable title="Uplod" v-model="showUploadPictures">
    <el-form ref="custForm">
      <el-row>
        <!-- 图片   :headers="headerObj"-->
        <el-col :span="12">
          <el-upload
            v-if="isPhoto"
            class="upload-demo"
            action="#"
            multiple
            :limit="5"
            accept=".jpg,.png,.jpeg"
            :http-request="HttpRequest"
            :on-success="HttpRequesSuccess"
            :before-upload="handleBeforeUpload"
            :on-remove="handleRemove"
            list-type="picture"
          >
            <el-button type="primary" v-if="photos.length < 5">Click to upload</el-button>
            <template #tip>
              <div class="el-upload__tip">jpg/png files with a size less than 1Mb.</div>
            </template>
          </el-upload>

          <el-upload
            v-else
            v-model:file-list="tallys"
            class="upload-demo"
            action="#"
            :limit="5"
            accept=".pdf"
            :http-request="HttpRequest"
            :on-success="HttpRequesSuccess"
            :on-remove="handleRemove"
            :before-upload="handleBeforeUpload"
          >
            <el-button type="primary" v-if="tallys.length < 5">Click to upload</el-button>
            <template #tip>
              <div class="el-upload__tip">pdf files with a size less than 1Mb.</div>
            </template>
          </el-upload>
        </el-col>
      </el-row>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="uploadPicturesCancel">{{ $t("ship.button.cancel") }}</el-button>
        <el-button type="primary" @click="submitUploadForm">{{ $t("ship.button.submit") }}</el-button>
      </span>
    </template>
  </el-dialog>
  <el-dialog :width="500" destroy-on-close draggable title="DownLoad" v-model="showDownLoadPictures">
    <el-row :gutter="24">
      <!-- 图片 -->
      <div class="demo-image__preview" v-if="isPhoto" v-for="(item, index) in photos" :key="index">
        <el-col :span="6">
          <el-image style="width: 100px; height: 100px" :src="item" fit="cover" @click="handlePreview(item)" />
        </el-col>
      </div>
      <transition-group v-else class="upload-file-list el-upload-list el-upload-list--text" name="el-fade-in-linear" tag="ul">
        <li :key="index" class="el-upload-list__item ele-upload-list__item-content" v-for="(url, index) in tallys">
          <el-link :href="url" :underline="false" target="_blank">
            <span class="el-icon-document" @click="downloadFileHandel(url)"> {{ getFileName(url) }} </span>
          </el-link>
        </li>
      </transition-group>
    </el-row>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="downLoadPicturesCancel">{{ $t("ship.button.cancel") }}</el-button>
        <!-- <el-button type="primary" @click="submitUploadForm">{{ $t("ship.button.submit") }}</el-button> -->
      </span>
    </template>
  </el-dialog>
  <el-popover :visible="visible" :width="300" :popper-style="{left:'40%',top:'40%',zIndex:'9999'}">
    <p>Are you sure to delete this?</p>
    <div style="text-align: right; margin: 0">
      <el-button size="small" text @click="visible = false">cancel</el-button>
      <el-button size="small" type="primary" @click="deleteImageOk">
        confirm
      </el-button>
    </div>
  </el-popover>
  <FileUpload ref="fileUploadRef" :fileType="fileType" @update:modelValue="updateFileUpload" />
  <PreViewPdfUpload v-model="viewPdfvisible" :pdf-url="pdfUrl" :pdf-name="pdfName" />
</template>
<script lang="ts" setup name="measuredDimension">
import { ref, onMounted, reactive, nextTick } from "vue";
import service from "@/utils/request";
import { ElNotification, ElMessageBox, ElMessage } from "element-plus";
import PreViewPdfUpload from './PreViewPdfUpload.vue'
import type {  UploadUserFile } from "element-plus";
import { useTableDrag } from '@/hooks/useHooks'
const { tableRef, proxy } = useTableDrag();
import { downloadFile } from "@/utils/downloadFile";
import { COS_CDN_URL, convertUrl } from "@/utils/tencentCos";
import { downloadCosImg } from "@/utils/tencentCos";
import { useRouter } from 'vue-router'
const router = useRouter()
const custForm = ref(null);
const dialogTitle = ref("");
const viewPdfvisible = ref(false);
const pdfUrl = ref<string>("");
const pdfName = ref<string>("");
const initForm = {
  id: null,
  brand: null,
  name: null,
  evType: null,
  cargoType: null,
  description: null,
  measureLength: null,
  measureWidth: null,
  measureHeight: null,
  weight: null,
  vesselVoyage: null,
  remark: null
};
const formParam = reactive(Object.assign({}, initForm));

const total = ref(0);

const rules = ref({
  portName: [{ required: true, message: "Port Name is required" }],
  portCode: [{ required: true, message: "Port Code is required" }],
  measureLength: [{ required: true, message: "Length(m) is required" }],
  measureWidth : [{ required: true, message: "Width(m) is required" }],
});
const evTypes = ["Non-EV", "BEV", "HEV", "PHEV", "EREV", "FCV", "EV", "OTHER"];
const types = ["passenger car","SUV","Light Truck"];
const queryParams = reactive({
  pageNum: 1,
  pageSize: 20,
  name: null,
  brand: null,
  orderByColumn: undefined,
  isAsc: undefined
});

let urlmap = {};
const brands = ref([] as any)
const listData = ref([]);
const refreshTable = async () => {
  let result = await service.get("/shipping/vehicleModel/getMeasureTable", {
    params: queryParams
  });

  listData.value = result.data;
  urlmap={}
    Object.keys(listData.value).forEach(key => {
     let photos=listData.value[key].photos
     if(photos){
          Object.keys(photos).forEach(key2 => {
              let tt=photos[key2]
              photos[key2]= convertUrl( photos[key2])
              urlmap[photos[key2]]= tt
          })
     }
    })
  total.value = result.total;
};
const resetQuery = (data) => {
    Object.assign(queryParams, data)
    refreshTable()
}
const dialogFormVisible = ref(false);

const editClickEvent = (row: any) => {
  dialogTitle.value = "Update Measured Dimension";
  dialogFormVisible.value = true;
  isAdd = false;
  Object.keys(initForm).forEach(k => (formParam[k] = row[k]));
};

let isAdd = false;

const addClickEvent = () => {
  dialogTitle.value = "Add Measured Dimension";
  isAdd = true;
  dialogFormVisible.value = true;
  Object.assign(formParam, initForm);
};

const resetForm = () => {
  // @ts-ignore
  custForm.value.resetFields();
};

const submitForm = () => {
  // @ts-ignore
  custForm.value.validate(async valid => {
    if (!valid) {
      // @ts-ignore
      ElNotification.warning({
        title: "Prompt information",
        message: "verification not success！",
        position: "bottom-right"
      });
      return;
    }

    await service[isAdd ? "post" : "put"]("shipping/vehicleModel", formParam);
    // @ts-ignore
    ElNotification.success({
      title: "Prompt information",
      message: "save successful!",
      position: "bottom-right"
    });
    dialogFormVisible.value = false;
    refreshTable();
  });
};

const pageQuery = async e => {
  queryParams.pageNum = e.page;
  queryParams.pageSize = e.limit;
  refreshTable();
};

const search = () => {
  refreshTable();
};

 
const pdfPreviewHandle = (file) => {
      pdfUrl.value =encodeURI(convertUrl(file))
      if(file.includes('pdf')){
        window.open(router.resolve({ path: '/pdfView/index', query: { pdfUrl: pdfUrl.value} }).href, '_blank')
      }else{
        convertUrlDownload(file)
      }
    }
const convertUrlDownload =(url) => {
    ElMessageBox.confirm("Confirm to download the file？", "Confirmation Information", {
    type: "warning",
    confirmButtonText: "Confirm",
    cancelButtonText: "Cancel"
  }).then(async () => {
		let a = document.createElement('a');      //创建一个a标签用来跳转
		a.href = convertUrl(url)
		// a.target = '_blank'; 
		//a.download = "xixi.zip";                  //设置下载文件的文件名和文件格式
		document.body.appendChild(a);             //将标签DOM，放置页面
		a.click();
		document.body.removeChild(a);

  });
}
const handleSortChange = async (column: any) => {
  queryParams.orderByColumn = column.prop;
  queryParams.isAsc = column.order; //动态取值排序顺序
  refreshTable();
};

const removeClickEvent = id => {
  ElMessageBox.confirm("Confirm to Remove the data？", "Confirmation Information", {
    type: "warning",
    confirmButtonText: "Confirm",
    cancelButtonText: "Cancel"
  }).then(async () => {
    await service.delete(`shipping/vehicleModel/${id}`);

    refreshTable();
    // @ts-ignore
    ElNotification.success({
      title: "Prompt information",
      message: "Delete successfully!",
      position: "bottom-right"
    });
  });
};
const fileUploadRef = ref(null);
const fileType = ref([".pdf"]);
const uploadFileForm = () => {
  proxy.$refs["fileUploadRef"].dialogUploadFileForm();
};
const updateFileUpload= (data: any) => {
  refreshTable();
};
const showUploadPictures = ref(false);
const isPhoto = ref(false);
const photos = ref<UploadUserFile[]>([]);
const tallys = ref<UploadUserFile[]>([]);
const submitUploadForm = async () => {
  // @ts-ignore
  const params = {
    id: recordData.value.id,
    photos: recordData.value.photos,
    tallys: recordData.value.tallys
  };

  //await service["put"]("shipping/vehicleModel/update", params);
  // // @ts-ignore
  ElNotification.success({
    title: "Prompt information",
    message: "save successful!",
    position: "bottom-right"
  });
  uploadPicturesCancel();
  refreshTable();
};
const uploadPictures = (row: any, val: any) => {
  showUploadPictures.value = true;
  initForm.id = row.id;
  isPhoto.value = val;

  // photos.value = (row.photos && JSON.parse(row.photos)) || [];
  // tallys.value = (row.tallys && JSON.parse(row.tallys)) || [];
};

const uploadFile = async event => {
  if (event.target == null || event.target.files[0] == null) {
    return;
  }
  const formData = new FormData();
  formData.append("file", event.target.files[0]);
  await service["post"]("shipping/vehicleModel/uploadFile", formData);
};


const handleBrand= async(value)=>{
  const isOptionSelected = brands.value.some(option => option.value === value);
      if (!isOptionSelected) {
        console.log(value)
        await service.post("/shipping/brand", {name:value})
      }  
}

let cargo_type = reactive([])
let fuel_type = reactive([])
onMounted(async () => {
  refreshTable();
  let result = await service.get("/shipping/brand/list");
  if (result) {
     brands.value = result.data;
  }

  const res = await proxy.useDict("cargo_type","fuel_type");
  cargo_type = res.cargo_type
  fuel_type = res.fuel_type
});
const handleChange = (record, type) => {
  isPhoto.value = type;
  recordData.value = record;
};
const handleBeforeUpload = file => {
  const maxSize = 1 * 1024 * 1024; // 10MB，根据你的需求设置最大文件大小
  if (file.size > maxSize) {
    ElMessage.warning(`File size ${maxSize / (1024 * 1024)}MB extends the limit`);
    return false;
  }

  if (isPhoto.value && !["image/png", "image/jpeg"].includes(file.type)) {
    ElMessage.warning(`Only support jpg,jpeg format`);
    return false;
  }

  if (!isPhoto.value && !["application/pdf"].includes(file.type)) {
    ElMessage.warning(`Only support pdf format`);
    return false;
  }

  return true;
};

const loading = ref(false);
const photoList = ref<any>([]);
const tollysList = ref<any>([]);
const HttpRequest = async data => { 
  const maxSize = 1 * 1024 * 1024; // 10MB，根据你的需求设置最大文件大小
  if (data?.file?.size > maxSize) {
    ElMessage.warning(`File size${maxSize / (1024 * 1024)}MB  extends the limit`);
    return false;
  }

  if (isPhoto.value && !["image/png", "image/jpeg", "image/png"].includes(data?.file.type) && data) {
    ElMessage.warning(`Only support jpg,jpeg format`);
    return false;
  }

  if (!isPhoto.value && !["application/pdf"].includes(data?.file.type) && data) {
    ElMessage.warning(`Only support pdf format`);
    return false;
  }

  loading.value = true;

  // new 一个formdata 对象 将我们的参数和文件赋值进去
  const formdata = new FormData();
  formdata.append("file", data.file);
  formdata.append("id", String(recordData.value.id));
  formdata.append("seqNo", "1");

  let res = await service.post(
    isPhoto.value ? "/shipping/vehicleModel/uploadPhoto" : "/shipping/vehicleModel/uploadTally",
    formdata
  );
  if (isPhoto.value) {
    photos.value[photos.value.length - 1] = res.data.url;
    photoList.value.push(res.data.url);
    if(recordData.value.photos)
        recordData.value.photos.push(res.data.url);
  } else {
    tallys.value[tallys.value.length - 1] = res.data.url;
    tollysList.value.push(res.data.url);
    if(recordData.value.tallys)
        recordData.value.tallys.push(res.data.url);
  }
};
const handleSuccess = () => {
  submitUploadForm();
};
const handleRemove = (file, fileList) => {
  if (isPhoto.value) {
    photoList.value = photoList.value.filter(item => item.url != file.url);
  } else {
    tollysList.value = tollysList.value.filter(item => item.url != file.url);
  }
};
const uploadRemove = (file, row) => {
  ElMessageBox.confirm("Confirm to Remove the file？", "Confirmation Information", {
    type: "warning",
    confirmButtonText: "Confirm",
    cancelButtonText: "Cancel"
  }).then(async () => {
    row.tallys= row.tallys.filter(item => item != file); 

    let params = {
      id: row.id,
      url: file,
    };
    await service["post"]("/shipping/vehicleModel/deleteFile", params);

    params = {
      id: row.id,
      photos: row.photos,
      tallys: row.tallys
    };
    // @ts-ignore
    ElNotification.success({
      title: "Prompt information",
      message: "delete the file success!",
      position: "bottom-right"
    });
  });
};

const showDownLoadPictures = ref(false);
const uploadPicturesCancel = () => {
  showUploadPictures.value = false;
  photos.value = [];
  tallys.value = [];
};
const downLoadPicturesCancel = () => {
  showDownLoadPictures.value = false;
  photos.value = [];
  tallys.value = [];
};
const downloadPictures = (row: any, type) => {
  if (type == false && !row.tallys) {
    ElMessage.warning(`No file to download!`);
    return;
  }
  if (type && !row.photos) {
    ElMessage.warning(`No photo to download!`);
    return;
  }
  isPhoto.value = type;
  showDownLoadPictures.value = true;
  photos.value = row.photos || [];
  tallys.value = row.tallys || [];
};
const handlePreview = (url: any) => {
  downloadCosImg(url, getFileName(url));
};
// 获取文件名称
function getFileName(name) {
  // 如果是url那么取最后的名字 如果不是直接返回
  if (name.lastIndexOf("/") > -1) {
    return name.slice(name.lastIndexOf("/") + 1);
  } else {
    return name;
  }
}
const recordData = ref();
const visible=ref(false);
function clickImage(record:any) {
  recordData.value = record;
  nextTick(() => {
    let wrapper = document.getElementsByClassName("el-image-viewer__actions__inner");
    // 添加下载图片按钮
    let downloadBtn = document.createElement("i");
    downloadBtn.setAttribute("class", "el-icon");
    downloadBtn.innerHTML =
      '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 1024 1024"><path fill="currentColor" d="M160 832h704a32 32 0 1 1 0 64H160a32 32 0 1 1 0-64m384-253.696 236.288-236.352 45.248 45.248L508.8 704 192 387.2l45.248-45.248L480 584.704V128h64z"></path></svg>';
    downloadBtn.addEventListener("click", cusClickHandler);

    wrapper[0].appendChild(downloadBtn);

    // 添加删除图片按钮
    let deleteBtn = document.createElement("i");
    deleteBtn.setAttribute("class", "el-icon");
    deleteBtn.innerHTML =
      ' <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 1024 1024"><path fill="currentColor" d="M352 192V95.936a32 32 0 0 1 32-32h256a32 32 0 0 1 32 32V192h256a32 32 0 1 1 0 64H96a32 32 0 0 1 0-64zm64 0h192v-64H416zM192 960a32 32 0 0 1-32-32V256h704v672a32 32 0 0 1-32 32zm224-192a32 32 0 0 0 32-32V416a32 32 0 0 0-64 0v320a32 32 0 0 0 32 32m192 0a32 32 0 0 0 32-32V416a32 32 0 0 0-64 0v320a32 32 0 0 0 32 32"></path></svg>';

    deleteBtn.addEventListener("click", deleteImage);
    wrapper[0].appendChild(deleteBtn);
  });
}
const isShowImage = ref(false);
const deleteImage= async()=> {
      //visible.value = true;

	  ElMessageBox.confirm("Confirm to Delete the file？", "Delete  Information", {
		type: "warning",
		confirmButtonText: "Confirm",
		cancelButtonText: "Cancel",
		customClass:"measured",
		modalClass:"measured_delete",
		customStyle:{"z-index":3000}
	  }).then(async () => {
          deleteImageOk()

	  });
}
const  deleteImageOk=async()=>{

  let url=recordData.value.photos[imgIndex.value]
  url=urlmap[url]

  const params = {
    id: recordData.value.id,
    url: url,
  };
  await service["post"]("/shipping/vehicleModel/deleteFile", params);

  let close = document.querySelector(".el-image-viewer__close");  
  close.click();
  visible.value = false;
  refreshTable()
}
function cusClickHandler() {
  const imgUrl = recordData.value.photos[imgIndex.value];
  downloadCosImg(imgUrl, getFileName(imgUrl));
}
const imgIndex = ref(0);
function switchImage(e) {
  imgIndex.value = e;
}
function downloadFileHandel(url) {
  downloadFile(url,  getFileName(url));
}
 //删除
 const isDel = ref(false)
  //防抖函数
  const debounce = (fn, t) => {
    let delay = t || 300
    let timer
    return function () {
      let args = arguments
      if (timer) {
        clearTimeout(timer)
      }
      let callNow = !timer
      timer = setTimeout(() => {
        timer = null
      }, delay)
      if (callNow) fn.apply(this, args)
    }
  }
  const mouseoverHandle = debounce((status:boolean) => {
    isDel.value = status
  }, 500)
const handlePreviewPdf = (pdfurl: string, pdfname: string) => {

  pdfUrl.value = pdfurl;
  pdfName.value = pdfname;
  viewPdfvisible.value = true;
}
</script>
<style lang="scss" scoped>
.el-image-viewer__wrapper {
  /* 修改遮罩层的样式 */
  width: 80%;
  height: 80%;
  left: 15%;
  top: 10%;
}
.el-table__expand-column .cell {
  display: none;
}
::v-deep.el-table td.el-table__cell div{
    text-align: center;
  }
.c-expand {
  color: #888;
  display: flex;
  align-items: center;
  justify-content: center;
  font-weight: 700;
  cursor: pointer;
  width: 100%;
  height: 100%;
}
.cell{
  display: flex;
}
.c-expand i {
  font-size: 16px;
}
.c-expand i.expand {
  font-size: 16px;
  transform: rotate(90deg);
  transition: all 0.25s;
}
.upload-file-uploader {
  margin-bottom: 5px;
}
.el-upload-list{
  margin: 0;
  
}
.el-icon-download {
  width: 22px;
  height: 22px;
  color: #fff;
}
.upload-file-list .el-upload-list__item {
  line-height: 2;
  padding: 0 5px;
  position: relative;
}
.upload-file-list .ele-upload-list__item-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
  color: inherit;
}
.ele-upload-list__item-content-action .el-link {
  margin-right: 10px;
}
.upload-demo {
  display: inline-block;
}
.el-icon-download{
  cursor: pointer;
  color: black;
}
.diff-measure{
  color: red;
  font-style: italic;
  font-weight: 800;
  font-size: 14px
}

.fielupload span {
    color: #409eff; 
}
.fielupload {
    display: flex;
    position: relative;
    padding: 0 6px;
    padding-left: v-bind('isDel?"20px":"6px"');
    border: 1px solid #ccc;
    height: 24px;
    border-radius: 2px;
    margin-top: 4px;
    margin-right: 2px;
  }
  .image_content{
    display: flex;
    justify-content: flex-start;
  }

</style>
<style>
  .measured_delete{
      z-index:9999 !important;
  }
</style>